package com.huajx.cseek.face.server;

import com.ha.facecamera.configserver.*;
import com.huajx.core.server.HbootServer;
import com.huajx.core.server.annonation.MinaServer;
import com.huajx.core.server.config.HbootServerConfig;
import com.huajx.cseek.face.handler.DataReceivedHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@MinaServer(name = "cseekData", port = 10002)
public class CseekDataServer implements HbootServer {
    private static final Logger logger = LoggerFactory.getLogger(CseekConfigServer.class);

    private static DataServer dataServer;
    public static final int DEFAULT_PORT = 10001;
    private boolean isRunning;

    private String serverName;
    private int port;

    private String describe;

    @Override
    public void start() {
        isRunning = startDataServer(port);

        if (isRunning) {
            logger.info("{} 数据服务启动完毕,{}", serverName, port);
            dataServer.onCameraConnected((val) -> {
                logger.info("{} 设备已连接-数据端口:{}, {}", serverName, val, describe);
            });

            dataServer.onCaptureCompareDataReceived((data) -> {
                logger.info("收到抓拍对比数据\\n\\t:{}", serverName);
                DataReceivedHandler.handler(data);
            });

            dataServer.onCameraDisconnected((val) -> {
                logger.info("{} 设备已断开-数据端口:{}, {}", serverName, val, describe);
            });

            dataServer.onAuthing((time, username, password) -> {
                // XXX 如果要校验用户名密码，请使用如下代码
                //return username.equals("xiaohe") && Util.judgeRegPassword(time, "123456", password);
                logger.info("{} 收到鉴权消息username=>{} password=>{}", serverName, username, password);
                return true;
            });
        }
    }

    @Override
    public void stop() {
        if (!isRunning) {
            logger.warn("{}服务器已经停止！", serverName);
        } else {
            dataServer.stop();
        }
    }

    @Override
    public boolean isRunning() {
        return isRunning;
    }

    @Override
    public void config(HbootServerConfig config) {
        this.port = config.getPort() <= 80 ? DEFAULT_PORT : config.getPort();
        this.serverName = config.getName();
        this.describe = config.getDescribe();
    }

    /**
     * 启动数据服务器
     *
     * @param uploadProt 人脸相机TCP上传端口
     * @return 服务启动成功true
     */
    public static Boolean startDataServer(int uploadProt) {
        dataServer = new DataServer();
        DataServerConfig dsc = new DataServerConfig();
        dsc.connectStateInvokeCondition = ConnectStateInvokeCondition.DeviceNoKnown;
        return dataServer.start(uploadProt, dsc);
    }
}
